package consul

import (
	"common/config"
	"github.com/google/uuid"
	"github.com/hashicorp/consul/api"
	"log"
)

type ServiceRegistration struct {
	Name    string
	Address string
	Port    int
	Tags    []string
	ID      string // 可选，如果为空则自动生成
}

// RegisterService 注册服务到Consul
func RegisterService(reg ServiceRegistration) {
	if reg.ID == "" {
		reg.ID = uuid.NewString()
	}

	registration := &api.AgentServiceRegistration{
		ID:      reg.ID,
		Name:    reg.Name,
		Address: reg.Address,
		Port:    reg.Port,
		Tags:    reg.Tags,
	}

	filter := `Service==` + reg.Name

	withFilter, _ := config.Consul.Agent().ServicesWithFilter(filter)

	if len(withFilter) != 0 {
		log.Println("已经注册过了")
	} else {
		err := config.Consul.Agent().ServiceRegister(registration)
		if err != nil {
			log.Fatalln("注册失败")
		}
		log.Println("注册成功")
	}
}
